package com.wzapp.sitposture.authentication.config;

import com.wzapp.sitposture.authentication.endpoint.CustomizedAuthenticationEntryPoint;
import com.wzapp.sitposture.authentication.exception.WebResponseExceptionTranslator;
import com.wzapp.sitposture.authentication.service.CustomizedDefaultTokenServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;
import java.util.concurrent.TimeUnit;

/**
 * 功能: <br/>
 *
 * @author ql
 * @version 0.4
 * @create 2018-05-30 16:43
 **/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private DataSource dataSource;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private WebResponseExceptionTranslator webResponseExceptionTranslator;

    /**
     * 功能:用来配置令牌端点(Token Endpoint)的安全约束 <br/>
     *
     * @param security
     * @return void
     * @author ql
     * @create 2018-05-29 16:25
     **/
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .authenticationEntryPoint(new CustomizedAuthenticationEntryPoint());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
        endpoints.tokenStore(tokenStore);
        endpoints.userDetailsService(userDetailsService);
        endpoints.setClientDetailsService(clientDetailsService);
        //配置TokenServices参数
//        DefaultTokenServices tokenServices = new DefaultTokenServices();
        CustomizedDefaultTokenServices tokenServices = new CustomizedDefaultTokenServices();
        tokenServices.setTokenStore(tokenStore);
        tokenServices.setClientDetailsService(clientDetailsService);
        tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
        // 设置access_token永不过期
//        tokenServices.setAccessTokenValiditySeconds(-1);
//        tokenServices.setRefreshTokenValiditySeconds(-1);
        //设置为fasle则不支持刷新token
//        tokenServices.setSupportRefreshToken(false);
        //设置每次刷新refreshToken都重新刷新，不能复用,如果失效或者丢失则需要重新登录
        tokenServices.setReuseRefreshToken(false);
//        tokenServices.setReuseRefreshToken(true);
        tokenServices.setSupportRefreshToken(true);
//        // 设置access_token过期时间 36hours过期
        tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(7));
//        //设置reresh_token过期时间 90天过期
        tokenServices.setRefreshTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(180));
        endpoints.tokenServices(tokenServices);
        //自定义异常拦截
        endpoints.exceptionTranslator(webResponseExceptionTranslator);
    }

    /**
     * 用来配置客户端详情服务（ClientDetailsService），客户端详情信息在这里进行初始化，你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息。
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

    /**
     * 功能: 声明TokenStore实现<br/>
     *
     * @param
     * @return org.springframework.security.oauth2.provider.token.TokenStore
     * @author ql
     * @create 2018-05-30 17:07
     **/
    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    /**
     * 功能: 声明 ClientDetails实现<br/>
     *
     * @param
     * @return org.springframework.security.oauth2.provider.ClientDetailsService
     * @author ql
     * @create 2018-05-30 17:07
     **/
    @Bean
    public ClientDetailsService clientDetails() {
        return new JdbcClientDetailsService(dataSource);
    }

    @Bean
    @Primary
    public CustomizedDefaultTokenServices tokenServices() {
        CustomizedDefaultTokenServices tokenServices = new CustomizedDefaultTokenServices();
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenStore(tokenStore);
        return tokenServices;
    }

}
